
var fs = require('fs'); //引用文件系统模块

const path = require('path');

var get_client_ip = function(req) {

	var ipStr = req.headers['x-forwarded-for'] ||
		req.ip ||
		req.connection.remoteAddress ||
		req.socket.remoteAddress ||
		req.connection.socket.remoteAddress || '';
	var ipReg = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/;
	if (ipStr.split(',').length > 0) {
		ipStr = ipStr.split(',')[0]
	}
	var ip = ipReg.exec(ipStr);
	if (ip) {
		return ip[0];
	} else {
		return ipStr;
	}

}
let getTime = opt => {
	let d = new Date();
	return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate() + " " + d.getHours() + ":" + d
	.getMinutes() + ":" + d.getSeconds()
}

let checkCsrf = async (req, res) => {
	let d = new Date();
	if (req.headers["csrf"]) {
		//检查有效性 
		try {
			let csrf = aes.decrypt(req.headers["csrf"].split("_")[0]); //时间戳+随机数
			let _csrf = aes.decrypt(req.headers["csrf"].split("_")[1]); //时间
			let rd_csrf = await rds.get(rds.CSRF + csrf)
			if (rd_csrf.data) {
				res.status(400).send("非法请求")
				return false
			} else {
				//校验csrf
				let timeStmp = parseFloat(csrf.split("_")[0]),
					timeStr = _csrf;
				let year = d.getFullYear(),
					month = d.getMonth() + 1,
					day = d.getDate();
				let sTime = new Date(year + "/" + month + "/" + day + " " + _csrf).getTime();
				if (timeStmp - sTime > 1000) {
					res.status(400).send("bad request..")
				} else {
					rds.set(rds.CSRF + csrf, 1, 300)
					return true
				}
			}
		} catch (e) {
			console.log(e)
			res.status(400).send("bad request.")
			return false
		}
	} else {

		res.status(400).send("bad request.no csrf")
		return false
	}
}

function readFileList() {

	var files = fs.readdirSync(path.join(process.cwd(),"/apublic"));
	

	let api_router = [];
	files.forEach(function(itm, index) {
		try {
			let file = require("../apublic/" + itm);
			for (let k in file) {
				let api = {
					path: "/" + k.toLowerCase(),
					callback: (req, res) => {

						return new Promise(function(resolve, reject) {
							file[k](req.body).then(data => {
								res.send(data);

							}, err2 => {
								res.send({
									code: 500,
									msg: JSON.stringify(
										err2)
								});

							})
						});

					}
				}
				api_router.push(api)
			}
		} catch (e) {
			console.log(e)
		}
	})

	return {
		api_router: api_router
	}

}




module.exports = readFileList()
